package com.herr.springboot.data.jpamulti.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;


@Configuration
@EnableJpaRepositories(basePackages = "com.herr.springboot.data.jpamulti.dao2",entityManagerFactoryRef = "secondaryLocalContainerEntityManagerFactoryBean",transactionManagerRef = "secondPlatformTransactionManager")
public class JpaConfigSecondary {
    @Autowired
    @Qualifier("dsSecondary")
    DataSource dsSecondary;

    @Autowired
    JpaProperties jpaProperties;

    @Bean
    LocalContainerEntityManagerFactoryBean secondaryLocalContainerEntityManagerFactoryBean(EntityManagerFactoryBuilder builder) {
        return builder.dataSource(dsSecondary)
                .properties(jpaProperties.getProperties())
                .persistenceUnit("pu2")
                .packages("com.herr.springboot.data.jpamulti.entity")
                .build();
    }

    @Bean
    PlatformTransactionManager secondPlatformTransactionManager(EntityManagerFactoryBuilder builder) {
        return new JpaTransactionManager(secondaryLocalContainerEntityManagerFactoryBean(builder).getObject());
    }
}
